from django.shortcuts import render,redirect,HttpResponse
from django import forms
from app03 import models
from django.conf import settings
from app03.utils.pegination import Pegination
from app03.utils.bootrsap import BootrsapForm,BootrsapModelForm


def travel_list(request):
    if request.method=='GET':
        #搜索框
        seach_list={}
        seach_data=request.GET.get('q','')
        #根据地点搜索判断
        if seach_data:
            seach_list['user__contains']=seach_data
        #获取数据库中的信息
        data_list=models.Travel.objects.filter(**seach_list)
        #分页
        page_object=Pegination(request,data_list)
        coxtent={
            'page_string':page_object.html(),  #生成页数据
            'seach_data':seach_data,  #生成页码
            'data_list':page_object.page_mun
        }
        return render(request,'travel_list.html',coxtent)

class TravelModelForm(BootrsapModelForm):
    bootrsap_exitis_forms = ['img']
    class Meta:
        model=models.Travel
        fields='__all__'
def travel_add(request):
    title='旅游文件上传'
    if request.method=='GET':
        form=TravelModelForm()
        return render(request,'travel_add.html',{'form':form,'title':title})
    form=TravelModelForm(data=request.POST,files=request.FILES)
    print(form)
    if form.is_valid():
        # print('t')
        form.save()
        return redirect('/travel/list/')
    return render( request, 'travel_add.html', {'form': form, 'title': title} )

class TravelEditModelForm(BootrsapModelForm):
    bootrsap_exitis_forms = ['img']
    class Meta:
        model=models.Travel
        exclude=['img']

def travel_edit(request,nid):
    title='编辑列表'
    row_i=models.Travel.objects.filter(id=nid).first()
    if request.method=='GET':
        form=TravelEditModelForm(instance=row_i)
        return render(request,'travel_edit.html',{'form':form,'title':title})
    form=TravelEditModelForm(data=request.POST,instance=row_i)
    if form.is_valid():
        form.save()
        return redirect('/travel/list/')
    return render( request, 'travel_edit.html', {'form': form, 'title': title} )


def travel_delete(request,nid):
    models.Travel.objects.filter(id=nid).delete()
    return redirect('/travel/list/')